<template>
  <div class="template-backup-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>模板文件备份</h3>
          <div class="header-actions">
            <el-button type="primary" @click="handleCreateBackup" :loading="creating">
              <el-icon><Upload /></el-icon>
              创建备份
            </el-button>
            <el-button @click="loadBackupList">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 备份列表 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="backupList"
          stripe
          style="width: 100%;"
          empty-text="暂无备份数据"
        >
        <el-table-column prop="fileName" label="备份文件名" min-width="350" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="file-info">
              <el-icon class="file-icon"><Document /></el-icon>
              <span>{{ row.fileName }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="fileSize" label="文件大小" width="140" align="center">
          <template #default="{ row }">
            {{ formatFileSize(row.fileSize) }}
          </template>
        </el-table-column>

        <el-table-column prop="description" label="备份描述" min-width="300" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.description || '无描述' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" width="200" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="handleDownload(row)"
              :loading="row.downloading"
            >
              <el-icon><Download /></el-icon>
              下载
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建备份对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建模板备份"
      width="600px"
      @close="resetCreateForm"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createFormRules"
        label-width="100px"
      >
        <el-form-item label="备份名称" prop="name">
          <el-input
            v-model="createForm.name"
            placeholder="请输入备份名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="备份描述" prop="description">
          <el-input
            v-model="createForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入备份描述（可选）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="备份范围" prop="scope">
          <el-radio-group v-model="createForm.scope">
            <el-radio label="all">全部模板文件</el-radio>
            <el-radio label="portal">仅门户模板</el-radio>
            <el-radio label="admin">仅管理后台模板</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="压缩格式" prop="format">
          <el-select v-model="createForm.format" placeholder="请选择压缩格式">
            <el-option label="ZIP" value="zip" />
            <el-option label="TAR.GZ" value="tar.gz" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmCreate" :loading="creating">
            确定创建
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Upload, Refresh, Document, Download, Delete } from '@element-plus/icons-vue'
import { templateBackupApi } from '@/api/template-backup'

// 响应式数据
const loading = ref(false)
const creating = ref(false)
const createDialogVisible = ref(false)
const createFormRef = ref<FormInstance>()

// 备份列表
const backupList = ref<any[]>([])

// 分页
const pagination = ref({
  page: 1,
  size: 20,
  total: 0
})

// 创建表单
const createForm = ref({
  name: '',
  description: '',
  scope: 'all',
  format: 'zip'
})

// 表单验证规则
const createFormRules: FormRules = {
  name: [
    { required: true, message: '请输入备份名称', trigger: 'blur' },
    { min: 2, max: 100, message: '备份名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  scope: [
    { required: true, message: '请选择备份范围', trigger: 'change' }
  ],
  format: [
    { required: true, message: '请选择压缩格式', trigger: 'change' }
  ]
}

// 方法
const loadBackupList = async () => {
  loading.value = true
  try {
    const response = await templateBackupApi.getBackupList({
      page: pagination.value.page,
      size: pagination.value.size
    })
    
    if (response.code === 0) {
      backupList.value = response.data.list || []
      pagination.value.total = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取备份列表失败')
    }
  } catch (error) {
    console.error('获取备份列表失败:', error)
    ElMessage.error('获取备份列表失败')
  } finally {
    loading.value = false
  }
}

const handleCreateBackup = () => {
  createDialogVisible.value = true
  // 生成默认备份名称
  const now = new Date()
  const timestamp = now.toISOString().slice(0, 19).replace(/[:-]/g, '').replace('T', '_')
  createForm.value.name = `template_backup_${timestamp}`
}

const handleConfirmCreate = async () => {
  if (!createFormRef.value) return
  
  try {
    await createFormRef.value.validate()
    creating.value = true
    
    const response = await templateBackupApi.createBackup(createForm.value)
    if (response.code === 0) {
      ElMessage.success('备份创建成功')
      createDialogVisible.value = false
      loadBackupList()
    } else {
      ElMessage.error(response.msg || '备份创建失败')
    }
  } catch (error) {
    console.error('创建备份失败:', error)
    ElMessage.error('创建备份失败')
  } finally {
    creating.value = false
  }
}

const handleDownload = async (row: any) => {
  try {
    row.downloading = true
    const response = await templateBackupApi.downloadBackup(row.id)
    
    // 创建下载链接
    const blob = new Blob([response], { type: 'application/octet-stream' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = row.fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载备份失败:', error)
    ElMessage.error('下载备份失败')
  } finally {
    row.downloading = false
  }
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除备份文件"${row.fileName}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await templateBackupApi.deleteBackup(row.id)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      loadBackupList()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除备份失败:', error)
      ElMessage.error('删除备份失败')
    }
  }
}

const resetCreateForm = () => {
  createForm.value = {
    name: '',
    description: '',
    scope: 'all',
    format: 'zip'
  }
  createFormRef.value?.resetFields()
}

const handleSizeChange = (size: number) => {
  pagination.value.size = size
  pagination.value.page = 1
  loadBackupList()
}

const handleCurrentChange = (page: number) => {
  pagination.value.page = page
  loadBackupList()
}

// 工具函数
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDateTime = (dateTime: string): string => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const getStatusType = (status: string): string => {
  const statusMap: Record<string, string> = {
    'success': 'success',
    'failed': 'danger',
    'creating': 'warning'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    'success': '成功',
    'failed': '失败',
    'creating': '创建中'
  }
  return statusMap[status] || '未知'
}

onMounted(() => {
  loadBackupList()
})
</script>

<style scoped>
.template-backup-container {
  padding: 20px;
  width: 100%;
  min-width: 1400px;
  overflow-x: auto;
  height: 100vh;
  box-sizing: border-box;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  color: #409eff;
  font-size: 16px;
  flex-shrink: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表格容器样式 */
.table-container {
  width: 100%;
  overflow-x: auto;
  min-width: 1400px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header-wrapper) {
  background-color: #f8f9fa;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 响应式设计 */
@media (max-width: 1600px) {
  .template-backup-container {
    min-width: 1200px;
  }

  .table-container {
    min-width: 1200px;
  }
}

@media (max-width: 1400px) {
  .template-backup-container {
    min-width: 1000px;
  }

  .table-container {
    min-width: 1000px;
  }
}

@media (max-width: 1200px) {
  .template-backup-container {
    min-width: 800px;
    padding: 16px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
